package com.lhgray.sglhome.presentation.ui.activity

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.BaseQuickAdapter
import com.freightoa.foundation.utlis.KeyBoardUtil
import com.freightoa.foundation.utlis.LoadingDialog
import com.freightoa.foundation.utlis.showToast
import com.google.android.material.button.MaterialButton
import com.lhgray.sglhome.R
import com.lhgray.sglhome.domain.model.ImageBean
import com.lhgray.sglhome.presentation.ui.adapter.UploadPhotoAdapter
import com.lhgray.sglhome.presentation.viewModel.UploadPhotoViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import okhttp3.Dispatcher
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

@AndroidEntryPoint
class UploadPhotoActivity : AppCompatActivity(), View.OnClickListener,
    BaseQuickAdapter.OnItemClickListener<ImageBean> {

    private val requestPermissionLauncher =
        registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted: Boolean ->
            if (isGranted) {
                dispatchTakePictureIntent()
            } else {
                this.showToast("Permission denied")
            }
        }

    private val pickImage =
        registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(6)) { uris: List<Uri>? ->
            if (uris?.isNotEmpty() == true) {
                val urisSix = uris.take(6)
                uploadPhotoAdapter?.submitList(urisSix.map {
                    ImageBean(1, imageUri = it)
                })
            }
        }
    private val takePictureLauncher =
        registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
            if (success) {
                loadingDialog.show()
                currentPhotoUri?.let { photoUri ->
                    lifecycleScope.launch {
                        viewModel.addWatermarkToImage(this@UploadPhotoActivity, photoUri)
                            .collect {
                                loadingDialog.dismiss()
                                uploadPhotoAdapter?.add(ImageBean(1, imageUri = it))
                            }
                    }
                }

            } else this.showToast("Photo Failed")
        }
    private var uploadPhotoAdapter: UploadPhotoAdapter? = null
    private lateinit var viewModel: UploadPhotoViewModel
    private var currentPhotoUri: Uri? = null
    private var editSubject: EditText? = null
    private var editDetail: EditText? = null
    private lateinit var loadingDialog: LoadingDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_upload_photo)
        viewModel = ViewModelProvider(this)[UploadPhotoViewModel::class.java]
        viewModel.setSourceData(
            intent.getStringExtra("source_table"),
            intent.getStringExtra("source_id"),
            intent.getStringExtra("longitude") ?: "",
            intent.getStringExtra("latitude") ?: ""
        )
        // 使用方式
        loadingDialog = LoadingDialog(this)
        findViewById<TextView>(R.id.base_title_black).setOnClickListener(this)
        findViewById<MaterialButton>(R.id.layout_btn_image).setOnClickListener(this)
        findViewById<MaterialButton>(R.id.layout_btn_photo).setOnClickListener(this)
        findViewById<CardView>(R.id.layout_cardview).setOnClickListener(this)
        editSubject = findViewById(R.id.edit_subject)
        editDetail = findViewById(R.id.edit_detail)
        val layoutRecycler = findViewById<RecyclerView>(R.id.layout_recycler)
        layoutRecycler.apply {
            layoutManager =
                GridLayoutManager(this@UploadPhotoActivity, 3, LinearLayoutManager.VERTICAL, false)
            uploadPhotoAdapter = UploadPhotoAdapter()
            uploadPhotoAdapter?.setOnItemClickListener(this@UploadPhotoActivity)
            adapter = uploadPhotoAdapter
        }
        viewModel.data.observe(this) {
            loadingDialog.dismiss()
            this.showToast(getString(if (it) R.string.uploaded_success else R.string.uploaded_failed))
            if (it) {
                startActivity(Intent(this, SuccessPageActivity::class.java))
                finish()
            }
        }

    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.base_title_black -> finish()
            R.id.layout_cardview -> {
                savePhoto()
            }

            R.id.layout_btn_image -> {
                selectImage()
            }

            R.id.layout_btn_photo -> {
                pickPhoto()
            }
        }
    }

    /**
     * 上传图片的方法
     */
    private fun savePhoto() {
        val subject = editSubject?.text.toString().trim()
        if (subject.isEmpty()) {
            this.showToast("Please enter a title. Title is required.")
            return
        }
        val items = uploadPhotoAdapter?.items
        loadingDialog.show()
        viewModel.savePhoto(items, subject, editDetail?.text.toString().trim() ?: "")
    }

    private fun pickPhoto() {
        if ((uploadPhotoAdapter?.items?.size ?: 0) >= 6) {
            this.showToast(getString(R.string.bus_Cannot))
            return
        }
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            dispatchTakePictureIntent()
        } else {
            requestPermissionLauncher.launch(Manifest.permission.CAMERA)
        }
    }


    private fun selectImage() {
        pickImage.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))

    }


    override fun onClick(adapter: BaseQuickAdapter<ImageBean, *>, view: View, position: Int) {

    }

    private fun dispatchTakePictureIntent() {
        val photoFile: File? = try {
            createImageFile()
        } catch (ex: IOException) {
            null
        }
        photoFile?.also {
            currentPhotoUri = FileProvider.getUriForFile(
                this,
                this.packageName + ".fileprovider",
                it
            )
            if (currentPhotoUri != null) {
                takePictureLauncher.launch(currentPhotoUri!!)
            }
        }
    }

    @Throws(IOException::class)
    private fun createImageFile(): File {
        val timeStamp: String =
            SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
            "JPEG_${timeStamp}_",
            ".jpg",
            storageDir
        )
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_UP) {
            val v = currentFocus
            // 如果不是落在EditText区域，则需要关闭输入法
            if (KeyBoardUtil.isHideKeyboard(v, ev)) {
                KeyBoardUtil.hideKeyBoard(this, v)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun onPause() {
        super.onPause()
        KeyBoardUtil.hideKeyBoard(this, currentFocus)
    }
}